<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="dialogFormVisible"
    :before-close="close"
    :title="title"
    width="800px"
    :top="'10vh'"
  >
    <el-form ref="form" :model="form" size="small" label-width="120px">
      <div class="custom-tips">
        基础设置
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            label="数据项名称"
            prop="name"
            :rules="[{ required: true, message: '请输入数据项名称', trigger: 'blur' }]"
            style="width: 100%"
          >
            <el-input v-model="form.name" clearable placeholder="请输入数据项名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="数据源"
            prop="dataSql.id"
            :rules="[{ required: true, message: '请选择数据源', trigger: 'change' }]"
            style="width: 100%"
          >
            <el-select v-model="form.dataSql.id" clearable placeholder="请选择数据源">
              <el-option
                v-for="item in dataSource"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="custom-tips">
        查询sql <span style="color: #bd2c00">注意：参数请以${}包裹，参数名称要和参数设置项一一对应</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            label="查询SQL"
            prop="sqlDate"
            :rules="[{ required: true, message: '请输入查询SQL', trigger: 'blur' }]"
            style="width: 100%"
          >
            <el-input
              v-model="form.sqlDate"
              type="textarea"
              clearable
              placeholder="请输入查询SQL,查询参数请以${}包裹，参数名称要和参数设置中的设置项对应。"
              :autosize="{ minRows: 4}"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="custom-tips">
        参数设置
        <div class="button-add">
          <el-button type="text" icon="el-icon-plus" @click="doAdd">新增</el-button>
        </div>
      </div>
      <el-row v-for="(item,index) in items" :key="'item-'+index" :gutter="20" style="border-bottom: 1px solid #eeeeee;margin-bottom: 10px">
        <el-col :span="12">
          <el-form-item
            label="备注名称"
            style="width: 100%"
          >
            <el-input v-model="item.name" placeholder="请输入备注名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="参数名称"
            style="width: 100%"
          >
            <el-input v-model="item.code" placeholder="请输入参数名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="取值类型"
            style="width: 100%"
          >
            <el-select v-model="item.valueType" clearable placeholder="请选择取值类型">
              <el-option
                v-for="item in params"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="item.valueType !==1 && item.valueType !== 6 && null !== item.valueType" :span="12">
          <el-form-item
            label="格式"
            style="width: 100%"
          >
            <el-input v-model="item.dateType" placeholder="请输入日期/时间格式" clearable />
          </el-form-item>
        </el-col>
        <el-col v-if="item.valueType ==3 || item.valueType === 5" :span="12">
          <el-form-item
            label="时间"
            style="width: 100%"
          >
            <el-input-number v-model="item.time" placeholder="请输入时间" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="测试值"
            style="width: 100%"
          >
            <el-input v-model="item.testValue" placeholder="请输入测试值" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button type="text" icon="el-icon-delete" size="mini" @click="toDelete(item)">删除</el-button>
        </el-col>
      </el-row>
      <div class="custom-tips">
        解析项
        <div class="button-add">
          <el-button type="text" icon="el-icon-video-play" @click="doTest">获取解析项</el-button>
        </div>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            label="解析项"
            prop="jxx"
            :rules="[{ required: true, message: '解析项不能为空', trigger: 'change' }]"
            style="width: 100%"
          >
            <el-input
              v-model="form.jxx"
              type="textarea"
              readonly
              placeholder="请点击获取解析项按钮，获取解析字段"
              :autosize="{ minRows: 4}"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="close">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save('form')">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateObject, saveObject, analysisObject } from '@/api/portal/manager/entityData/index';
import { queryEnable } from '@/api/system/dataSource';
import { queryAllParams } from '@/api/portal/manager/setting/index';
export default {
  name: 'DbTaskManagerEntity',
  data() {
    return {
      title: '数据项管理',
      loading: false,
      dialogFormVisible: false,
      dataSource: [],
      params: [],
      items: [],
      form: {
        id: null,
        name: '',
        dataSql: {
          id: null
        },
        sqlDate: '',
        jxx: '',
        params: '',
        isDel: false
      }
    };
  },
  created() {
    this.initDataSource();
    this.initParams();
  },
  methods: {
    openEntity(data) {
      this.queryData = null;
      if (undefined !== data && undefined !== data.id && data.id !== null) {
        this.form = Object.assign({}, data);
        this.title = '修改信息';
        this.dialogFormVisible = true;
        if (undefined !== this.form.params && this.form.params !== null && this.form.params !== '') {
          this.items = JSON.parse(this.form.params);
        } else {
          this.items = [];
        }
        console.log(this.items);
      } else {
        this.title = '新增信息';
        this.dialogFormVisible = true;
        this.items = [];
      }
    },
    save(formName) {
      this.loading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id !== null && undefined !== this.form.id) {
            this.form.params = JSON.stringify(this.items);
            updateObject(this.form).then(res => {
              this.$message.success('更新成功！');
              this.close();
            }).catch(() => {
              this.loading = false;
              this.$message.error('更新失败！');
            });
          } else {
            this.form.params = JSON.stringify(this.items);
            saveObject(this.form).then(res => {
              this.$message.success('保存成功！');
              this.close();
              this.loading = false;
            }).catch(() => {
              this.loading = false;
              this.$message.error('保存失败！');
            });
          }
        } else {
          this.loading = false;
          console.log('error submit!!');
          return false;
        }
      });
    },
    doAdd() {
      const item = { name: '', code: '', test: true, valueType: null, testValue: '', dateType: '', time: 0 };
      this.items.push(item);
      console.log(this.items);
    },
    toDelete(item) {
      const index = this.items.indexOf(item);
      if (index !== -1) {
        this.items.splice(index, 1);
      }
    },
    initParams() {
      queryAllParams().then(res => {
        const { data } = res;
        this.params = data;
      });
    },
    initDataSource() {
      queryEnable().then(res => {
        this.dataSource = res;
      });
    },
    doTest() {
      if (this.form.dataSql.id === null) {
        this.$message.warning('请选择数据源');
      } else if (this.form.sqlDate === '' || this.form.sqlDate === null) {
        this.$message.warning('请输入查询sql');
      } else {
        analysisObject({ list: this.items, data: this.form.dataSql.id, sql: this.form.sqlDate }).then(res => {
          const { data } = res;
          this.form.jxx = data;
        });
      }
    },
    close() {
      this.loading = false;
      Object.assign(this.$data.form, this.$options.data.call(this).form);
      Object.assign(this.$data.items, this.$options.data.call(this).items);
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    }
  }
};
</script>

<style scoped>
.custom-tips {
  width: 100%;
  min-height: 40px;
  line-height: 40px;
  text-align: left;
  padding: 8px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  margin-bottom: 10px;
}
.button-add {
  width: 50px;
  height: 40px;
  float: right;
  text-align: center;
  line-height: 40px;
  margin-right: 20px;
}
</style>
